package service

import (
	"sdc/repository/db/model"
	"time"

	"gorm.io/gorm"
)

// DonationQuery 捐款查询参数
type DonationQuery struct {
	UserID    uint64
	Status    int8
	StartTime string
	EndTime   string
	Page      int
	PageSize  int
}

// DonationStats 捐款统计
type DonationStats struct {
	TotalAmount     float64 `json:"total_amount"`      // 总捐款金额
	TotalCount      int64   `json:"total_count"`       // 总捐款次数
	ProjectCount    int64   `json:"project_count"`     // 参与项目数
	ThisMonthAmount float64 `json:"this_month_amount"` // 本月捐款
	ThisYearAmount  float64 `json:"this_year_amount"`  // 本年捐款
}

// GetDonationDetail 获取捐款详情
func (s *DonationService) GetDonationDetail(donationID uint64) (*model.Donation, error) {
	var donation model.Donation
	err := s.db.Preload("Project").
		Preload("User", func(db *gorm.DB) *gorm.DB {
			return db.Select("id, username, avatar") // 只选择需要的字段
		}).
		First(&donation, donationID).Error
	return &donation, err
}

// ListUserDonations 用户捐款列表
func (s *DonationService) ListUserDonations(query *DonationQuery) (donations []model.Donation, total int64, err error) {
	db := s.db.Model(&model.Donation{}).Where("user_id = ?", query.UserID)

	// 状态筛选
	if query.Status >= 0 {
		db = db.Where("payment_status = ?", query.Status)
	}

	// 时间范围筛选
	if query.StartTime != "" {
		db = db.Where("created_at >= ?", query.StartTime)
	}
	if query.EndTime != "" {
		db = db.Where("created_at <= ?", query.EndTime)
	}

	// 统计总数
	err = db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (query.Page - 1) * query.PageSize
	err = db.Preload("Project").
		Offset(offset).Limit(query.PageSize).
		Order("created_at DESC").
		Find(&donations).Error

	return donations, total, err
}

// GetUserDonationStats 获取用户捐款统计
func (s *DonationService) GetUserDonationStats(userID uint64) (*DonationStats, error) {
	var stats DonationStats

	// 基础查询条件
	baseQuery := s.db.Model(&model.Donation{}).
		Where("user_id = ? AND payment_status = ?", userID, 1) // 只统计支付成功的

	// 总捐款金额和次数
	err := baseQuery.Select("COALESCE(SUM(amount), 0) as total_amount, COUNT(*) as total_count").
		Scan(&stats).Error
	if err != nil {
		return nil, err
	}

	// 参与项目数
	err = baseQuery.Distinct("project_id").Count(&stats.ProjectCount).Error
	if err != nil {
		return nil, err
	}

	// 本月捐款
	now := time.Now()
	monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.Local)
	err = baseQuery.Where("created_at >= ?", monthStart).
		Select("COALESCE(SUM(amount), 0) as this_month_amount").
		Scan(&stats).Error
	if err != nil {
		return nil, err
	}

	// 本年捐款
	yearStart := time.Date(now.Year(), 1, 1, 0, 0, 0, 0, time.Local)
	err = baseQuery.Where("created_at >= ?", yearStart).
		Select("COALESCE(SUM(amount), 0) as this_year_amount").
		Scan(&stats).Error
	if err != nil {
		return nil, err
	}

	return &stats, nil
}
